<template>
  <el-dialog :model-value="true" :close-on-click-modal="true" :before-close="handleClose" append-to-body
    :title="titleObj[pageType]" width="532px">

    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="表单名称" prop="formName">
        <el-input v-model="formData.formName" placeholder="请输入表单名称" />
      </el-form-item>
      <el-form-item label="业务类型" prop="bizTypeId">
        <el-select v-model="formData.bizTypeId" placeholder="请选择业务类型" :disabled="['copy','edit'].includes(pageType)"
          @change="bizTypeChange" class="width-parent">
          <el-option v-for="item in bizTypeList" :key="item.id" :value="item.id" :label="item.typeName" />
        </el-select>
      </el-form-item>
      <el-form-item label="业务子类" prop="subBizTypeCode">
        <subBizSelect ref="subBizSelectRef" v-model="formData.subBizTypeCode" :bizTypeName="formData.bizTypeName"
          :checkStrictly="true" :multiple="false" :emitPath="false" />
        <!-- <el-cascader ref="subBizTypeRef" v-model="formData.subBizTypeId" class="width-parent"
          :disabled="formData.bizTypeId == ''" :options="subBizTypeList" :props="subBizTypeProps" placeholder="请选择业务子类"
          @change="subBizTypeChange">
          <template v-slot:empty>
            <span>{{ subBizNoDataText() }}</span>
          </template>
        </el-cascader> -->
      </el-form-item>
      <el-form-item label="业务性质" prop="tag" v-if="isShowTag">
        <el-select v-model="formData.tag" placeholder="请选择业务类型" class="width-parent"
          :disabled="formData.bizTypeId == '' || ['copy', 'edit'].includes(pageType)">
          <el-option v-for="item in bizTypeQualityList" :key="item.code" :value="item.code" :label="item.name" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="所属端口" prop="clientType">
                不需要端口和关联表单
                <el-select
                    v-model="formData.clientType"
                    placeholder="请选择所属端口"
                    class="width-parent"
                    @change="clientTypeChange"
                >
                    <el-option
                        v-for="item in clientTypeList"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                    />
                </el-select>
            </el-form-item> -->
      <!-- <el-form-item
                :label="`关联${formData.clientType == 'pc' ? '移动端' : 'PC端'}表单`"
                prop="relatedFormId"
            >
                <el-select
                    v-model="formData.relatedFormId"
                    placeholder="请选择关联表单"
                    :no-data-text="relateNoDataText()"
                    class="width-parent"
                >
                    <el-option
                        v-for="item in formList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.formName"
                    />
                </el-select>
            </el-form-item> -->
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button :loading="loading" type="primary" @click="handleSubmit">确定</el-button>
        <el-button @click="handleClose">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
/*
    * File Created: 2022-02-14 15:05:42
    * Author: yubaolin (yubaolin6@outlook.com)
    * Desc: 填报类表单配置 外层用v-if控制是否显示
    * Last Modified: 2022-02-14 15:08:33
    * Modified By: yubaolin (yubaolin6@outlook.com>)
    */
import { ref, reactive, toRefs } from "vue";
import api from '@/api/index'
import { ElMessage } from 'element-plus'
import { formatListToTree, statusText } from "@/util/index";

export default {
  props: {
    bizTypeList: {
      type: Array,
      default: () => []
    },
    pageType: {
      type: String,
      default: 'add'
    }
  },
  emits: ['refresh', 'close'],

  setup(props, { emit }) {
    const formRef = ref(null)
    const subBizTypeRef = ref(null)
    const state = reactive({
      isShowTag: false,
      loading: false,
      subBizSelectRef: null,
      formData: {
        bizTypeId: '',
        bizTypeCode: '',
        bizTypeName: '',
        clientType: 'pc',
        clientTypeName: 'PC端',
        formName: '',
        relatedFormId: '',
        relatedFormCode: '',
        subBizTypeId: '',
        subBizTypeCode: '',
        subBizTypeName: '',
        bizTypeQuality: '',
        tag: ''
      },
      rules: {
        formName: [
          { required: true, message: '请输入表单名称' }
        ],
        bizTypeId: [
          { required: true, message: '请选择业务类型' }
        ],
        subBizTypeCode: [
          { required: true, message: '请选择业务子类' }
        ],
        subBizTypeId: [
          { required: true, message: '请选择业务子类' }
        ],
        tag: [
          { required: true, message: '请选择业务性质' }
        ]
      },
      // 业务子类
      subBizTypeList: [],
      subBizTypeProps: {
        emitPath: false,
        value: 'id',
        label: 'subBizName',
      },
      // 所属端口
      // clientTypeList: [
      //     { value: 'pc', label: 'PC端' },
      //     { value: 'app', label: '移动端' },
      // ],
      // 关联表单列表
      formList: [],
      bizTypeQualityList: [],//业务性质
      titleObj: {
        'add': '创建表单',
        'copy': '复制为',
        'edit': '编辑表单'
      }
    })


    const methods = {
      // 获取业务性质
      getBizQualityList(tags) {
        api.reimbursement.getBizQualit(tags).then(res => {
          state.bizTypeQualityList = res
        })
      },

      // 请求业务子类列表
      requestSubBusinessTypeList(bizTypeName) {
        state.subBizTypeList = []
        if (!bizTypeName) {
          return
        }
        api.reimbursement.getSubTypeListByBizName(bizTypeName).then(data => {
          state.subBizTypeList = formatListToTree(data)
        })
      },
      // 查询关联表单
      requestFormList(clientType, subBizTypeCode) {
        state.formList = []
        if (!subBizTypeCode) {
          return
        }
        api.writeForm.unrelatedFormList({
          bizTypeCode: state.formData.bizTypeCode,
          subBizTypeCode: subBizTypeCode,
          clientType: clientType == 'pc' ? 'app' : 'pc',
        }).then(data => {
          state.formList = data
        })
      },
    }

    const handles = {
      handleClose() {
        emit('close')
      },
      handleSubmit() {
        formRef.value.validate(valid => {
          console.log(valid, 'validvalid')
          if (!valid) {
            return
          }

          state.loading = true
          let subObj = {}
          const tar = state.subBizSelectRef.getCurrentCheckedNode()

          if (tar && tar.length > 0) {
            subObj = {
              subBizTypeId: tar[0].data.id,
              subBizTypeName: tar[0].data.subBizName,
              subBizNamePath: tar[0].pathLabels.join("/"),
              subBizCodePath: tar[0].pathValues.join("/")
            }
            
          }
             console.log(subObj)
          const formData = { ...state.formData, ...subObj }

          // 赋值所属端口
          // const clientType = state.clientTypeList.find(item => item.value == formData.clientType)
          // formData.clientTypeName = clientType.label

          // 搜索关联表单，赋值表单编号
          // const formItem = state.formList.find(item => item.id == formData.relatedFormId)
          // if (formItem) {
          //     formData.relatedFormCode = formItem.formCode
          // }

          const interFaceObj = {
            'copy': 'copyWriteForm',
            'add': 'addWriteForm',
            'edit': 'updateWriteForm'
          }
          if (['copy', 'edit'].includes(props.pageType)) formData.originalWriteFormId = formData.id
          console.log(formData)
          api.writeForm[interFaceObj[props.pageType]](formData).then(() => {
            ElMessage.success('操作成功')
            state.loading = false
            emit('refresh')
            handles.handleClose()
            // todo 调整表单设计
          }).catch(() => {
            state.loading = false
          })
        })
      },
      // 业务类型改变
      bizTypeChange(bizTypeId) {

        const bizType = props.bizTypeList.find(item => item.id == bizTypeId)
        state.formData.bizTypeCode = bizType.typeCode
        state.formData.bizTypeName = bizType.typeName
        //state.formData.subBizTypeCode = ''

        // state.formData.relatedFormId = ''
        // methods.requestSubBusinessTypeList(bizType.typeName)
        // methods.requestFormList(state.formData.clientType, '')
        const tags = statusText(props.bizTypeList, bizTypeId, 'tags', 'id')

        state.isShowTag = tags == 'loanReimburse' ? true : false
  
        if (!state.isShowTag) {
        state.formData.tag = ''
        }

        if (tags) {
          methods.getBizQualityList(tags)
        }
      },
      // 业务子类改变
      subBizTypeChange(subBizId) {
        let data = subBizTypeRef.value.getCheckedNodes(true)[0].data
        state.formData.subBizTypeName = data.subBizName
        state.formData.subBizTypeCode = data.businessCode
        // state.formData.relatedFormId = ''
        // methods.requestFormList(data.businessCode)
      },
      // clientTypeChange(clientType) {
      //     methods.requestFormList(clientType, state.formData.subBizTypeCode);
      // },
      subBizNoDataText() {
        const formData = state.formData
        return formData.bizTypeId ? '无数据' : '请先选择业务类型'
      },
      relateNoDataText() {
        const formData = state.formData
        return formData.bizTypeId ? formData.subBizTypeCode ? '无数据' : '请先选择业务子类' : '请先选择业务类型'
      },

    }
    watch(() => state.formData.bizTypeId, (newVal, oldVal) => {
      console.log(newVal, oldVal, '监听')
      handles.bizTypeChange(newVal)
    },
      //深度监听
      { deep: true }
    )
    return {
      formRef,
      subBizTypeRef,
      ...toRefs(state),
      ...handles,
    }
  }
}
</script>
<style lang="scss">
.width-parent {
  width: 100%;
}
</style>
